#!/usr/bin/env node

import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

function removeConsoleFromFile(filePath) {
  if (!fs.existsSync(filePath)) {
    console.log(`文件不存在: ${filePath}`)
    return
  }

  let content = fs.readFileSync(filePath, 'utf-8')
  const originalLength = content.length
  const lines = content.split('\n')
  const cleanedLines = []

  let i = 0
  while (i < lines.length) {
    const line = lines[i]
    const trimmedLine = line.trim()

    // 检查是否是 console 调用开始（但不是 console.error）
    if (trimmedLine.match(/^console\.(log|info|warn|debug|trace)\s*\(/)) {
      // 找到 console 调用的结束
      let openParens = 0
      let consoleCallComplete = false
      let j = i

      while (j < lines.length && !consoleCallComplete) {
        const currentLine = lines[j]

        // 计算括号
        for (let char of currentLine) {
          if (char === '(') openParens++
          if (char === ')') openParens--
        }

        // 如果括号平衡且包含分号或者是最后一行，则认为 console 调用结束
        if (openParens === 0 && (currentLine.includes(';') || j === lines.length - 1)) {
          consoleCallComplete = true
          i = j + 1 // 跳过整个 console 调用
          break
        }
        j++
      }

      if (!consoleCallComplete) {
        // 如果没有找到完整的 console 调用，保留这一行
        cleanedLines.push(line)
        i++
      }
    } else {
      // 不是 console 调用，保留这一行
      cleanedLines.push(line)
      i++
    }
  }

  const cleanedContent = cleanedLines.join('\n')

  if (cleanedContent.length !== originalLength) {
    fs.writeFileSync(filePath, cleanedContent)
    console.log(`✅ 已清理 ${path.basename(filePath)} 中的 console 语句 (减少了 ${originalLength - cleanedContent.length} 字符)`)
  } else {
    console.log(`ℹ️ ${path.basename(filePath)} 中没有找到需要清理的 console 语句`)
  }
}

function removeConsoleFromDirectory(dirPath) {
  if (!fs.existsSync(dirPath)) {
    console.log(`目录不存在: ${dirPath}`)
    return
  }

  const files = fs.readdirSync(dirPath, { withFileTypes: true })
  
  files.forEach(file => {
    const fullPath = path.join(dirPath, file.name)
    
    if (file.isDirectory()) {
      removeConsoleFromDirectory(fullPath)
    } else if (file.name.endsWith('.js')) {
      removeConsoleFromFile(fullPath)
    }
  })
}

// 主执行逻辑
const distPath = path.join(path.dirname(__dirname), 'dist')

console.log('🧹 开始清理 console 语句...')

// 清理 dist 目录下的所有 JS 文件
removeConsoleFromDirectory(distPath)

console.log('🎉 console 语句清理完成！')
